import router, { routers } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import Vue from 'vue'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // determine whether the user has logged in
  // 获取token
  const hasToken = getToken()
  // 中断上一个页面的未完成的请求
  if (Vue.$httpRequestList.length > 0) { // 强行中断时才向下执行
    Vue.$httpRequestList.forEach(item => {
      item('interrupt')// 给个标志，中断请求
    })
  }
  // 已登录状态
  if (hasToken) {
    // 登录页直接跳到首页
    if (to.path === '/login') {
      // set page title
      document.title = getPageTitle(to.meta.title)
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasGetUserInfo = store.getters.username
      // 已获取用户信息
      if (hasGetUserInfo) {
        // 回调跳转
        const query = to.query
        if (query && query.state) {
          const state = query.state.split('-')
          if (state[0] && state[0] === '_pdd') {
            console.log(1)
            await store.dispatch('app/jumpUrl', {
              mode: '_pdd',
              id: state[1],
              page: state[2],
              per_page: state[3],
              code: query.code
            }).then(params => {
              next(params)
            }).catch(_ => {})
          }
        }
        // set page title
        document.title = getPageTitle(to.meta.title)
        // start loading
        store.commit('app/SET_LOADING', true)
        // start progress bar
        NProgress.start()
        next()
      } else {
        // set page title
        document.title = getPageTitle(to.meta.title)
        // start loading
        store.commit('app/SET_LOADING', true)
        // start progress bar
        NProgress.start()
        try {
          // get user info
          await store.dispatch('user/getInfo')
          if (store.getters.menus.length < 1) {
            global.antRouter = []
          } else {
            router.addRoutes(routers(store.getters.menus)) // 动态添加路由
            global.antRouter = store.getters.menus // 将路由数据传递给全局变量，做侧边栏菜单渲染工作
            next({
              ...to,
              replace: true
            })
          }
        } catch (error) {
          // remove token and go to login page to re-login
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(async(route) => {
  let leftMenus = []
  const menus = store.getters.menus
  for (let i = 0; i < menus.length; i++) {
    if (route.matched[1] && route.matched[1].path === menus[i].path) {
      leftMenus = menus[i].children || []
    }
  }
  // eslint-disable-next-line no-undef
  store.commit('user/SET_LEFT_MENUS', leftMenus)
  // finish progress bar
  NProgress.done()
})
